package cn.sdnu.database.service;

import java.util.List;
import java.util.concurrent.locks.ReentrantLock;

import cn.sdnu.database.utils.Utils;

/**
 * @author Master_Joe qiaoguangtong@aliyun.com
 */
public class Use {
	private static Use use = null;
	private static ReentrantLock lock = new ReentrantLock();
	/**
	 * 使用的数据库
	 */
	private String databaseUsed = null;

	private Use() {

	}

	public static Use getInstance() {
		if (use == null) {
			lock.lock();
			try {
				if (use == null) {
					use = new Use();
				}
			} finally {
				lock.unlock();
			}
		}
		return use;
	}

	public void sqlHandle(String sql) {
		if (sql.startsWith("use ")) {
			// 因为我们的sql语句的最后都有空格, 因此我们要使用sql.length() - 2;
			String databaseName = sql.substring(4, sql.length() - 2);
			List<String> databases = Utils.getDatabases();
			if (databases.contains(databaseName)) {
				databaseUsed = databaseName;
				System.out.println("Database changed");
			} else {
				System.out.println("ERROR: Unknown database '" + databaseName + "'");
			}
		} else {
			System.out.println("Error: You have some syntax error, please try again");
		}
	}

	/**
	 * 
	 * @return 当前使用的数据库, 当没有使用use [database name] 语句时, 则返回null;
	 */
	public String getDatabaseUsed() {
		return databaseUsed;
	}

}
